package com.example.secondhandshop.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.model.ItemModel;
import com.example.secondhandshop.ui.activity.ItemDetailActivity;
import com.example.secondhandshop.ui.activity.PublicProductsActivity;
import com.example.secondhandshop.ui.activity.SearchActivity;
import com.example.secondhandshop.ui.adapter.HomeGoodsAdapter;

import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
    private RecyclerView recyclerView;
    private ImageView imageView;
    private   TextView searchView;
    private HomeGoodsAdapter adapter;
    private List<Item> itemList;
    private ItemModel itemModel;
    private int currentPage = 1; // 当前页数
    private boolean isLoading = false; // 是否正在加载


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        imageView = view.findViewById(R.id.imageView);
        searchView = view.findViewById(R.id.search_view);

        itemList = new ArrayList<>();

        adapter = new HomeGoodsAdapter(itemList, item -> {
            // 处理点击事件，跳转到商品详细页面
            Intent intent = new Intent(getActivity(), ItemDetailActivity.class);
            intent.putExtra("itemId", item.getId());
            Log.d("HomeFragmentItem clicked", "Item clicked: " + item.getId());
            startActivity(intent);
        });

        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("HomeFragmentSearchView ", "SearchView clicked");
                // 启动另一个Activity
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), SearchActivity.class);
                    startActivity(intent);
                }
            }
        });

        //发布商品监听
       imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动另一个Activity
                if (getActivity() != null) {
                    Intent intent = new Intent(getActivity(), PublicProductsActivity.class);
                    startActivity(intent);
                }
            }
        });


        // 使用 GridLayoutManager 设置为两列
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        itemModel = new ItemModel();
        loadProducts(currentPage, 6, null, null); // 加载商品，指定当前页和页面大小

        // 下拉刷新
        SwipeRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            currentPage = 1; // 重置为第一页
            loadProducts(currentPage, 6, null, null); // 重新加载商品
            swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
        });

        // 上拉加载更多
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1) && !isLoading) {
                    currentPage++; // 页数加1
                    loadProducts(currentPage, 6, null, null); // 加载更多商品
                }
            }
        });

        return view;
    }

    private void loadProducts(int current, int size, String keyword, String typeId) {
        int userId = 624;
        isLoading = true; // 设置为正在加载

        itemModel.getItems(userId, current, size, keyword, typeId, new ItemModel.OnProductsFetchedListener() {

            @Override
            public void onSuccess(List<Item> items) {
                Log.e("HomeFragment", "onSuccess: " + items);
                // 确保在主线程中更新 UI
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (current == 1) {
                            itemList.clear(); // 清空列表以重新加载
                        }
                        itemList.addAll(items); // 添加新商品
                        adapter.notifyDataSetChanged(); // 刷新适配器
                        isLoading = false; // 设置为不再加载
                    });
                }
            }

            @Override
            public void onFailure(String error) {
                // 确保在主线程中更新 UI
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {

                        Toast.makeText(getContext(), "加载失败: " + error, Toast.LENGTH_SHORT).show();
                        isLoading = false; // 设置为不再加载
                    });
                }
            }
        });
    }

}